import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import { useStore } from "vuex";
import router from "../router";

// 创建 axios
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API +'/api',
  // baseURL: "http://localhost:5199/api",
  timeout: 10000,
  headers: {
    "Content-Type": "application/json;charset=UTF-8;",
  },
});

let loading;
let message;
//正在请求的数量
let requestCount = 0;
//显示loading
const showLoading = () => {
  if (requestCount === 0 && !loading) {
    loading = ElLoading.service({
      text: "加载中  ",
      background: "rgba(0, 0, 0, 0.7)",
      spinner: "el-icon-loading",
    });
  }
  requestCount++;
};

//隐藏loading
const hideLoading = () => {
  requestCount--;
  if (requestCount == 0) {
    loading.close();
  }
};

// 请求拦截 request
service.interceptors.request.use(
  (config) => {
    showLoading();
    // 用户请求头
    // config.headers.token = "";
    // config.headers.userId = "";

    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    // const token = window.localStorage.getItem('token');
    // token && (config.headers.Authorization = `Bearer ${token}`);

    const jwtToken = sessionStorage.getItem("jwt") || "";
    jwtToken && (config.headers.Authorization = `Bearer ${jwtToken}`);

    return config;
  },
  (err) => {
    hideLoading();
    Promise.reject(err);
  }
);

// 响应拦截 response
service.interceptors.response.use(
  (response) => {
    hideLoading();

    const respData = response.data;
    if (respData.success) {
      if (respData.code !== 0) {
        respData.success = false;
        ElMessage.warning(respData.message);
      }
      return respData;
    } else {
      ElMessage({
        message: `<p>错误代码: ${data.code}</p><p style="margin-top:5px;">错误信息: ${data.message}</p>`,
        dangerouslyUseHTMLString: true,
        type: "error",
        grouping: true,
        duration: 5000,
      });
      return Promise.reject(response);
    }
  },
  (error) => {
    hideLoading();
    //响应错误
    if (error.response && error.response.status) {
      const status = error.response.status;
      switch (status) {
        case 400:
          message = "请求错误";
          break;
        // 处理登录无效问题
        case 401:
          // message = '请求错误，未授权登录';
          message = "请先登录";
          sessionStorage.clear()
          router.push({ name: "Login" });
          console.log(router);
          // 移除过期token
          // window.localStorage.removeItem('token');
          break;
        case 404:
          message = "请求地址出错";
          break;
        case 408:
          message = "请求超时";
          break;
        case 500:
          message = "服务器内部错误!";
          break;
        case 501:
          message = "服务未实现!";
          break;
        case 502:
          message = "网关错误!";
          break;
        case 503:
          message = "服务不可用!";
          break;
        case 504:
          message = "网关超时!";
          break;
        case 505:
          message = "HTTP版本不受支持";
          break;
        default:
          message = "请求失败";
      }
      ElMessage.error(message);
      return Promise.reject(error);
    }
  }
);

export default service;
